package com.ht.api.call.func.impl.audience;

import javax.sql.DataSource;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.Entity;
import com.ht.api.db.task.HtTaskExecutor;
import com.ht.api.db.util.HtUtil;
import com.ht.api.task.AudienceInitTask;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 初始化人群
 * @author asq
 * @createTime 2025年3月19日 13:32:22
 */
public class AudienceInitFunctionCall implements IFunctionCall {

	@Override
	public String getName() {
		return "初始化人群";
	}

	@Override
	public JSONObject execute(LoginBean me, JSONObject param, AjaxResult result) {
		DataSource ds = me.getDataSource();
		
		String audienceId = param.getStr("audience_id");

		Entity audience = Entity.create("audience");
		audience.setMainId(audienceId);
		audience.set("init_status", 1);
		Db.insert(ds, audience);

		HtUtil.createLog(ds, audienceId, "开启初始化！");

		JSONObject taskParam = JSONUtil.createObj();
		taskParam.set("tenant_id", me.getTenantId());
		taskParam.set("audience_id", audienceId);
		taskParam.set("user_id", me.getLoginIdStr());
		HtTaskExecutor.submitTask(taskParam, new AudienceInitTask());

		// 返回客户端信息：已开启人群初始化，请稍后查看.
		return JSONUtil.createObj().set("info", "已开启人群初始化，请稍后查看.");
	}

}
